//
//  KRCateTagController.m
//  cookBook
//
//  Created by kuroken on 16/1/30.
//  Copyright © 2016年 kuroken. All rights reserved.
//

#import "KRCateTagController.h"
#import <MJExtension.h>
#import <MJRefresh.h>
#import <SVProgressHUD.h>
#import "KRHttpRecipeTool.h"
#import "KRConst.h"
#import "KRSearchGetListRecipeCell.h"
#import "KRNoNetCell.h"
#import "KRCateTagsListResult.h"
#import "KRSearchGetResultList.h"
#import "KRRecipeInfoController.h"

static NSUInteger const limit = 20;

@interface KRCateTagController ()

/** KRCateTagsListResult 模型 */
@property (nonatomic, strong) KRCateTagsListResult *result;

@property (nonatomic, assign) NSUInteger offset;

/** 当前请求 */
@property (nonatomic, strong) NSURLSessionDataTask *currentDataTask;
@property (nonatomic, assign, getter=isError) BOOL error;

@end

@implementation KRCateTagController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //  设置分隔线的位置和尺寸
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 110, 0, 0);
    
    // 去除多余的分隔线
    self.tableView.tableFooterView = [[UIView alloc] init];

    [self loadData];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (!self.result) {
        // 显示指示器
        [SVProgressHUD show];
        self.tableView.userInteractionEnabled = NO;
        self.tableView.scrollEnabled = NO;
    }
}

- (void)dealloc
{
    NSLog(@"%s", __func__);
}

/**
 *  上拉刷新控件
 */
- (void)setupFooterRefresh
{
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    [footer setTitle:@"没有更多数据" forState:MJRefreshStateNoMoreData];
    self.tableView.mj_footer = footer;
}

- (void)loadMoreData
{
    [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRSearchGetList;
        requestParams[@"tagid"] = self.tagID;
        requestParams[@"limit"] = [NSString stringWithFormat:@"%d", (int)limit];
        requestParams[@"offset"] = [NSString stringWithFormat:@"%d", (int)self.offset];
        
    } success:^(NSURLSessionDataTask *task, id json) {
//        KRLog(@"%@", json);
        KRCateTagsListResult *result = [KRCateTagsListResult mj_objectWithKeyValues:json[@"result"]];
        NSArray *listArray = result.list;
        [self.result.list addObjectsFromArray:listArray];
        
        self.offset += listArray.count;
        
        if (self.offset >= [self.result.count integerValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        [self.tableView reloadData];
        
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        self.offset -= limit;
        KRLog(@"%@, %@", self, error);
        self.error = YES;
        if ([self.tableView.mj_footer isRefreshing]) {
            [self.tableView.mj_footer endRefreshing];
        }
    }];
}


- (void)loadData
{
    self.offset = 0;
    [SVProgressHUD show];
    self.tableView.userInteractionEnabled = NO;
    self.tableView.scrollEnabled = NO;

    self.currentDataTask = [KRHttpRecipeTool getParams:^(NSString *__autoreleasing *method, NSMutableDictionary *requestParams) {
        *method = KRSearchGetList;
        requestParams[@"tagid"] = self.tagID;
        requestParams[@"limit"] = [NSString stringWithFormat:@"%d", (int)limit];
        requestParams[@"offset"] = [NSString stringWithFormat:@"%d", (int)self.offset];
        
    } success:^(NSURLSessionDataTask *task, id json) {
        if (self.currentDataTask != task) return;

        // 上拉刷新控件
        [self setupFooterRefresh];

        self.error = NO;
        self.tableView.scrollEnabled = YES;
        if (task != self.currentDataTask) return;

        self.result = [KRCateTagsListResult mj_objectWithKeyValues:json[@"result"]];

        self.offset += self.result.list.count;
        
        [self.tableView reloadData];
        
        if (self.offset >= [self.result.count integerValue]) {
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }
        
        [SVProgressHUD dismiss];
        self.tableView.userInteractionEnabled = YES;
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (task != self.currentDataTask) return;
        
        self.error = YES;
        [self.tableView reloadData];
        [SVProgressHUD dismiss];
        self.tableView.userInteractionEnabled = YES;
        
        [self.tableView.mj_footer removeFromSuperview];
        KRLog(@"%@, %@", self, error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (self.isError) return 1; // 请求失败
    if (!self.result) return 0;
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.isError) return 1;
    
    return self.result.list.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (self.isError) {
        KRNoNetCell *cell = [KRNoNetCell cellWithTableView:tableView];
        [cell setNoNetHint:@"网速不给力,无法加载"];
        return cell;
    }
    
    KRSearchGetListRecipeCell *cell =[KRSearchGetListRecipeCell cellWithTableView:tableView];
    cell.recipe = self.result.list[indexPath.row];
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isError) return [UIScreen mainScreen].bounds.size.height - KRTopBarHeight;

    return 85;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.isError) {
        self.error = NO;
        [self.tableView reloadData];
        [self loadData];
        return;
    }
    
    if (self.result.list.count){ // list
        KRRecipeInfoController *infoVc = [[KRRecipeInfoController alloc] init];
        infoVc.recipeID = self.result.list[indexPath.row].list_recipeID;
        [self.navigationController pushViewController:infoVc animated:YES];
    }
}

@end